<template>
  <!-- 资产点检工单表单弹窗 -->
  <div>
    <el-dialog
      :close-on-click-modal="false"
      v-model="visibleDialog"
      :title="props.title"
      width="1200px"
      draggable
      @close="closeDialog"
      :append-to-body="true"
    >
      <h4 class="mb-[20px]">标准作业项</h4>
      <el-descriptions
        v-show="props.isReadonly"
        class="margin-top w-full"
        title=""
        :column="4"
        size="large"
        border
      >
        <el-descriptions-item>
          <template #label>
            <div class="cell-item">产品号</div>
          </template>
          <div style="width: 100%; word-break: break-all">
            {{ sopstandardList.productCode || "" }}
          </div>
        </el-descriptions-item>
        <el-descriptions-item>
          <template #label>
            <div class="cell-item">工序</div>
          </template>
          <div style="width: 100%; word-break: break-all">
            {{ sopstandardList.processName || "" }}
          </div>
        </el-descriptions-item>

        <el-descriptions-item>
          <template #label>
            <div class="cell-item">作业编号</div>
          </template>
          <div style="width: 100%; word-break: break-all">
            {{ sopstandardList.standardCode || "" }}
          </div>
        </el-descriptions-item>
        <el-descriptions-item>
          <template #label>
            <div class="cell-item">作业名称</div>
          </template>
          <div style="width: 100%; word-break: break-all">
            {{ sopstandardList.standardName || "" }}
          </div>
        </el-descriptions-item>

        <el-descriptions-item>
          <template #label>
            <div class="cell-item">编制人</div>
          </template>
          <div style="width: 100%; word-break: break-all">
            {{ sopstandardList.standardCompilePersonnel || "" }}
          </div>
        </el-descriptions-item>
        <el-descriptions-item>
          <template #label>
            <div class="cell-item">审核人</div>
          </template>
          <div style="width: 100%; word-break: break-all">
            {{ sopstandardList.standardExaminePersonnel || "" }}
          </div>
        </el-descriptions-item>
        <el-descriptions-item>
          <template #label>
            <div class="cell-item">批准人</div>
          </template>
          <div style="width: 100%; word-break: break-all">
            {{ sopstandardList.standardRatifyPersonnel || "" }}
          </div>
        </el-descriptions-item>
        <el-descriptions-item>
          <template #label>
            <div class="cell-item">备注</div>
          </template>
          <div style="width: 100%; word-break: break-all">
            {{ formData.remarks || "" }}
          </div>
        </el-descriptions-item>
        <el-descriptions-item>
          <template #label>
            <div class="cell-item">产品流水号</div>
          </template>
          <div style="width: 100%; word-break: break-all">
            {{ formData.remarks || "" }}
          </div>
        </el-descriptions-item>
        <el-descriptions-item>
          <template #label>
            <div class="cell-item">计划单号</div>
          </template>
          <div style="width: 100%; word-break: break-all">
            {{ formData.remarks || "" }}
          </div>
        </el-descriptions-item>
        <el-descriptions-item>
          <template #label>
            <div class="cell-item">任务单号</div>
          </template>
          <div style="width: 100%; word-break: break-all">
            {{ formData.remarks || "" }}
          </div>
        </el-descriptions-item>
      </el-descriptions>

      <template #header v-if="!props.isReadonly">
        <el-button type="success" plain @click="handleAdd">
          <i-ep-plus />
          新增
        </el-button>
      </template>
      <div class="formTable" style="margin-top: 20px">
        <el-table
          :data="tableData"
          style="width: 100%"
          :key="Math.random"
          max-height="25vh"
          :header-cell-style="{ textAlign: 'center' }"
          border
        >
          <el-table-column
            label="作业项编号"
            props="sopItemCode"
            min-width="150"
            align="left"
          >
            <template #default="{ $index, row }">
              {{ row.sopItemCode }}
            </template>
          </el-table-column>
          <el-table-column
            label="作业项名称"
            props="sopItemName"
            min-width="150"
            align="left"
          >
            <template #default="{ $index, row }">
              {{ row.sopItemName }}
            </template>
          </el-table-column>
          <el-table-column
            label="标准值类型"
            props="standardValue"
            min-width="150"
            align="center"
          >
            <template #default="{ $index, row }">
              {{ row.standardValue }}
            </template>
          </el-table-column>
          <el-table-column
            label="上限值"
            props="standardMaxValue"
            min-width="100"
            align="right"
          >
            <template #default="{ $index, row }">
              {{ row.standardMaxValue }}
            </template>
          </el-table-column>
          <el-table-column
            label="下限值"
            props="standardMinValue"
            min-width="100"
            align="right"
          >
            <template #default="{ $index, row }">
              {{ row.standardMinValue }}
            </template>
          </el-table-column>
          <el-table-column
            label="检验值"
            props="sopItemValue"
            min-width="150"
            align="right"
          >
            <template #default="{ $index, row }">
              {{ row.sopItemValue }}
            </template>
          </el-table-column>
          <el-table-column
            label="结果"
            props="sopItemResult"
            min-width="150"
            align="center"
          >
            <template #default="{ $index, row }">
              {{ row.sopItemResult ? "正常" : "异常" }}
            </template>
          </el-table-column>
          <el-table-column
            label="附件"
            props="images"
            min-width="150"
            align="center"
          >
            <template #default="{ $index, row }">
              <span
                style="
                  text-decoration: underline;
                  cursor: pointer;
                  color: #509ee7;
                "
                @click="openDialogdetail(row)"
                >查看</span
              >
            </template>
          </el-table-column>
        </el-table>
      </div>
      <h4 class="mb-[20px] mt-[20px]" v-if="props.data.checkRuleId">
        标准校验规则
      </h4>
      <el-descriptions
        v-show="props.isReadonly"
        class="margin-top w-full"
        title=""
        :column="4"
        size="large"
        border
      >
        <el-descriptions-item>
          <template #label>
            <div class="cell-item">规则编号</div>
          </template>
          <div style="width: 100%; word-break: break-all">
            {{ qmscheckruleList.ruleCode || "" }}
          </div>
        </el-descriptions-item>
        <el-descriptions-item>
          <template #label>
            <div class="cell-item">规则名称</div>
          </template>
          <div style="width: 100%; word-break: break-all">
            {{ qmscheckruleList.ruleName || "" }}
          </div>
        </el-descriptions-item>

        <el-descriptions-item>
          <template #label>
            <div class="cell-item">事务类型</div>
          </template>
          <div style="width: 100%; word-break: break-all">
            {{
              qmscheckruleList.effectTypeCode
                ? useDictionary(
                    "transactionType",
                    qmscheckruleList.effectTypeCode
                  )
                : ""
            }}
          </div>
        </el-descriptions-item>
        <el-descriptions-item>
          <template #label>
            <div class="cell-item">规则级别</div>
          </template>
          <div style="width: 100%; word-break: break-all">
            {{
              qmscheckruleList.effectLevelCode
                ? useDictionary("EffectLevel", qmscheckruleList.effectLevelCode)
                : ""
            }}
          </div>
        </el-descriptions-item>

        <el-descriptions-item>
          <template #label>
            <div class="cell-item">检验类型</div>
          </template>
          <div style="width: 100%; word-break: break-all">
            {{ qmscheckruleList.checkTypeName || "" }}
          </div>
        </el-descriptions-item>
        <el-descriptions-item>
          <template #label>
            <div class="cell-item">周期个数</div>
          </template>
          <div style="width: 100%; word-break: break-all">
            {{ qmscheckruleList.weekNum || "" }}
          </div>
        </el-descriptions-item>
        <el-descriptions-item>
          <template #label>
            <div class="cell-item">连续抽检个数</div>
          </template>
          <div style="width: 100%; word-break: break-all">
            {{ qmscheckruleList.checkNum || "" }}
          </div>
        </el-descriptions-item>
        <el-descriptions-item>
          <template #label>
            <div class="cell-item">抽检频率次</div>
          </template>
          <div style="width: 100%; word-break: break-all">
            {{ qmscheckruleList.checkFrequency || "" }}
          </div>
        </el-descriptions-item>
      </el-descriptions>
      <template #footer>
        <div class="dialog-footer">
          <el-button
            v-if="!props.isReadonly"
            type="primary"
            :loading="loading"
            @click="handleSubmit"
            >确 定
          </el-button>
          <el-button @click="closeDialog">取 消</el-button>
        </div>
      </template>
    </el-dialog>
    <rawMaterialImage
      :visible="addDialog.visible"
      :title="addDialog.title"
      :data="addDialog.data"
      :is-readonly="addDialog.readvisible"
      @change-visible="changeVisible"
    />
  </div>
</template>

<script setup lang="ts">
import request from "@/utils/request";
import { useDictStoreHook } from "@/store/modules/dictionary";
import { useDictionary } from "@/utils/useTable"; // 引入
const dictionaryStore = useDictStoreHook();

defineOptions({
  name: "QMSQMSPOINTCHECKORDERADDORUPDATE",
  inheritAttrs: false,
});

const emit = defineEmits(["reset-table", "change-visible"]);

const props = defineProps({
  visible: {
    type: Boolean,
    default: () => {
      return false;
    },
  },
  title: {
    type: String,
    default: () => {
      return "";
    },
  },
  data: {
    type: Object,
    default: () => {
      return {};
    },
  },
  isReadonly: {
    type: Boolean,
    default: () => {
      return false;
    },
  },
});

/** 弹窗显示 **/
const visibleDialog = ref(false);
watch(
  () => props.visible,
  (newVal: boolean) => {
    visibleDialog.value = newVal;
  }
);

/** formData定义表单数据 */
const formRef = ref(ElForm);
let formData = reactive({
  id: "",
  version: "",
  assetKind: "",
  planNo: "",
  planName: "",
  orderNo: "",
  workTime: "",
  sopTypeId: "",
  sopTypeName: "",
  sopTypeCode: "",
  sopStandardId: "",
  sopStandardCode: "",
  sopStandardName: "",
  assetId: "",
  assetCode: "",
  assetName: "",
  orderStatus: "",
  remarks: "",
  executePersonId: "",
  executePersonName: "",
  checkPersonId: "",
  checkPersonName: "",
  deleted: "",
  createTime: "",
  createdUserId: "",
  createdUserName: "",
  lastUpdateTime: "",
  lastUpdatedUserId: "",
  lastUpdatedUserName: "",
  details: [
    {
      id: "",
      version: "",
      orderId: "",
      seq: "",
      sopItemId: "",
      sopItemCode: "",
      sopItemName: "",
      sopItemResult: "",
      sopItemStandard: "",
      createTime: "",
      createdUserId: "",
      createdUserName: "",
      lastUpdateTime: "",
      lastUpdatedUserId: "",
      lastUpdatedUserName: "",
      sopItemNameId: "",
      sopStandardId: "",
    },
  ],
});

/** rules规则 */
const rules = reactive({
  assetKind: [],
  orderNo: [],
  workTime: [],
  sopTypeId: [],
  sopTypeCode: [],
  sopStandardId: [],
  sopStandardCode: [],
  assetId: [],
  assetCode: [],
  assetName: [],
  orderStatus: [],
  remarks: [],
  executePersonId: [],
  executePersonName: [],
  checkPersonId: [],
  checkPersonName: [],
  deleted: [],
  createTime: [],
  createdUserId: [],
  createdUserName: [],
  lastUpdateTime: [],
  lastUpdatedUserId: [],
  lastUpdatedUserName: [],
  sonsopItemCode: [],
  sonsopItemName: [],
  sonsopItemResult: [],
  sonsopItemStandard: [],
});

const isValidated = ref(false);
/** 删除行 */
const handleDelete = (index: any) => {
  formData.details.splice(index, 1);
  isValidated.value && formRef.value.validate(() => {});
};

const details = {
  id: "",
  version: "",
  orderId: "",
  seq: "",
  sopItemId: "",
  sopItemCode: "",
  sopItemName: "",
  sopItemResult: "",
  sopItemStandard: "",
  createTime: "",
  createdUserId: "",
  createdUserName: "",
  lastUpdateTime: "",
  lastUpdatedUserId: "",
  lastUpdatedUserName: "",
  sopItemNameId: "",
  sopStandardId: "",
};

/** 添加行 */
const handleAdd = () => {
  let sondata = JSON.parse(JSON.stringify(details));
  formData.details.push(sondata);
};

/** 编辑时赋值 */
watch(
  () => props.data,
  async (newVal: any) => {
    if (newVal?.id) {
      await getTableData(newVal.orderId);
      await getSopstandard(newVal.sopStandardId);
      if (newVal.checkRuleId) {
        await getQmscheckrule(newVal.checkRuleId);
      }
    }
  }
);

/** 关闭表单弹窗 */
function closeDialog() {
  visibleDialog.value = false;
  emit("change-visible", false);
  // resetForm();
}

/** 重置表单 */
function resetForm() {
  formRef.value.resetFields();
  formRef.value.clearValidate();
  formData.details = [JSON.parse(JSON.stringify(details))];
  formData.id = "";
  formData.version = "";
  formData.assetKind = "";
  formData.orderNo = "";
  formData.planNo = "";
  formData.planName = "";
  formData.workTime = "";
  formData.sopTypeId = "";
  formData.sopTypeName = "";
  formData.sopTypeCode = "";
  formData.sopStandardId = "";
  formData.sopStandardCode = "";
  formData.sopStandardName = "";
  formData.assetId = "";
  formData.assetCode = "";
  formData.assetName = "";
  formData.orderStatus = "";
  formData.remarks = "";
  formData.executePersonId = "";
  formData.executePersonName = "";
  formData.checkPersonId = "";
  formData.checkPersonName = "";
  formData.deleted = "";
  formData.createTime = "";
  formData.createdUserId = "";
  formData.createdUserName = "";
  formData.lastUpdateTime = "";
  formData.lastUpdatedUserId = "";
  formData.lastUpdatedUserName = "";
}

const loading = ref(false);

const uploadApi = import.meta.env.VITE_APP_BASE_API;
// 预览url前缀
const upPreviewUrl = `${uploadApi}/system/fileCenter/preview/`;

const handlePictureCardPreview = (url: string) => {
  url = url?.replace("fileCenter/download/", "fileCenter/preview/");
  window.open(url);
};

/** 资产点检工单保存提交 */
function handleSubmit() {
  formRef.value.validate(async (valid: any) => {
    if (valid) {
      loading.value = true;
      const text = formData.id ? "编辑" : "新增";
      console.log("formData", toRaw(formData));
      await request({
        url: "/qms/qmspointcheckorder/save",
        method: "post",
        data: formData,
      }).finally(() => {
        loading.value = false;
      });
      ElMessage.success(text + `成功`);
      closeDialog();
      emit("reset-table", formData.id);
      isValidated.value = false;
    } else {
      isValidated.value = true;
    }
  });
}

async function getdetails() {
  let sondetails = await request({
    url: `/qms/qmspointcheckorder/getDetails`,
    method: "post",
    data: formData,
  }).finally(() => {
    loading.value = false;
  });
  formData.details = sondetails.data;
}

const addDialog = reactive({
  visible: false,
  readvisible: false,
  title: "",
  data: {},
  docType: "1",
});

// 查询详情
async function getInfo(id: string) {
  request({
    url: `/eam/eamCommonDoc/get/${id}`,
    method: "get",
  })
    .then((data) => {
      addDialog.data = data.data;
      addDialog.visible = true;
    })
    .catch((res) => {
      console.log(res);
    });
}

/** 打开资产型号表单弹窗 */
const assetTypeId = ref("");
function openDialog(roleObj?: Object) {
  if (roleObj) {
    addDialog.title = "修改原材料";
    getInfo(roleObj.id);
  } else {
    assetTypeId.value = searchParam.value.assetTypeId;
    addDialog.title = "新增原材料";
    addDialog.visible = true;
  }
  addDialog.readvisible = false;
}

/** 打开资产型号表单弹窗 详情 */
function openDialogdetail(roleObj?: any) {
  console.log(roleObj);

  addDialog.title = "原材料详情";
  // getInfo(roleObj.id);
  addDialog.data = roleObj.images;
  addDialog.visible = true;
  addDialog.readvisible = true;
}

function changeVisible(value: boolean, docType: string) {
  addDialog.visible = value;
  addDialog.data = {};
}

// 获取table列表
const tableData = ref([]);

async function getTableData(id: string) {
  await request({
    url: `/qms/qmspointcheckorder/getDetails`,
    method: "post",
    data: { id },
  }).then((data) => {
    tableData.value = data.data;
    console.log(tableData.value);
  });
}
// 获取标准作业规程列表
const sopstandardList = ref({});

async function getSopstandard(id: string) {
  await request({
    url: `/qms/qmssopstandard/get/${id}`,
    method: "get",
  }).then((data) => {
    sopstandardList.value = { ...data.data };
    console.log(sopstandardList.value);
  });
}
// 获取标准作业规则列表
const qmscheckruleList: any = ref({});

async function getQmscheckrule(id: string) {
  await request({
    url: `qms/qmscheckrule/get/${id}`,
    method: "get",
  }).then((data) => {
    qmscheckruleList.value = { ...data.data };
    console.log(qmscheckruleList.value);
  });
}
</script>

<style lang="scss" scoped>
h4 {
  font-weight: 400;
  color: #000;
  padding-left: 10px;
  font-size: 14px;
  line-height: 14px;
}

.formTable {
  :deep(.el-form-item) {
    margin-right: 0 !important;
  }
}

:deep(.el-dialog .el-dialog__body) {
  overflow-y: auto;
  height: 65vh;
}

:deep(.search-container .el-input.el-input--default.el-input--suffix) {
  // 固定宽度
  width: 190px !important;
}

:deep(.search-container .el-form-item--default .el-form-item__label) {
  // 固定宽度
  justify-content: end;
}
:deep(.el-descriptions__label.el-descriptions__cell.is-bordered-label) {
  min-width: 115px;
}
:deep(.el-descriptions__content.el-descriptions__cell.is-bordered-content) {
  min-width: 170px;
}
</style>
